﻿namespace Refract.Navigation
{
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.Reflection;
    using System.Threading;
    using System.Windows;
    using System.Windows.Navigation;

    using Refract.Composition;
    using Refract.Extensions;
    using Refract.MVVM;
    using Refract.Views;

    public class DynamicNavigationAsyncResult : IAsyncResult
    {
        #region Properties

        public object AsyncState
        {
            get; set;
        }

        public WaitHandle AsyncWaitHandle
        {
            get; set;
        }

        public bool CompletedSynchronously
        {
            get; set;
        }

        public bool IsCompleted
        {
            get; set;
        }

        public View View
        {
            get; set;
        }

        #endregion Properties
    }

    public class DynamicNavigationContentLoader : INavigationContentLoader
    {
        #region Constructors

        public DynamicNavigationContentLoader()
        {
            if (DesignerProperties.IsInDesignTool) return;

            CompositionInitializer.SatisfyImports(this);
        }

        #endregion Constructors

        #region Properties

        [Import]
        public INavigationService NavigationService
        {
            get; set;
        }

        #endregion Properties

        #region Methods

        public IAsyncResult BeginLoad(Uri targetUri, Uri currentUri, AsyncCallback userCallback, object asyncState)
        {
            var result = new DynamicNavigationAsyncResult() { AsyncState = asyncState };
            if (string.IsNullOrEmpty(targetUri.OriginalString))
            {
                result.CompletedSynchronously = true;
                result.IsCompleted = true;
                userCallback(result);
                return result;
            }

            NavigationService.GetView(targetUri, (v) =>
            {
                result.View = v;
                result.IsCompleted = true;
                userCallback(result);
            });

            return result;
        }

        public void CancelLoad(IAsyncResult asyncResult)
        {
            return;
        }

        public bool CanLoad(Uri targetUri, Uri currentUri)
        {
            return true;
        }

        public LoadResult EndLoad(IAsyncResult asyncResult)
        {
            var result = asyncResult as DynamicNavigationAsyncResult;
            var loadResult = new LoadResult(result.View);
            return loadResult;
        }

        #endregion Methods
    }
}